package com.itheima.stock.algorithm;

import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;
import org.joda.time.DateTime;
import java.util.Collection;
import java.util.Date;

/**
 * @Description 定义stock_rt_info 表的精准匹配逻辑
 */
public class StockRtInfoTablePreciseHandler implements PreciseShardingAlgorithm<Date> {
    /**
     * m-$->{2021..2022}.stock_rt_info_$->{1..12}
     * @param collection 当前逻辑表对应的所有的表名称集合： stock_rt_inf_1~stock_rt_inf_12
     * @param preciseShardingValue 封装了cur_time片键相关的信息
     * @return
     */
    @Override
    public String doSharding(Collection<String> collection, PreciseShardingValue<Date> preciseShardingValue) {
        //获取逻辑表名称
        String logicTableName = preciseShardingValue.getLogicTableName();
        //获取片键名
        String columnName = preciseShardingValue.getColumnName();
        //获取片键值
        Date curTime = preciseShardingValue.getValue();
        //根据传入的日期，获取对应的年，然后从数据库集合中过滤即可
        String curStr = new DateTime(curTime).toString("yyyyMM");
        //查找year对应的数据库
        String TableName = collection.stream().filter(tbName -> tbName.endsWith(curStr)).findFirst().get();
        return TableName;
    }
}
